<script setup lang="ts">
import { ref, onMounted, reactive,watch } from "vue";
import { ElMessage, ElForm, ElFormItem, ElCheckboxGroup, ElCheckbox, ElButton, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { setGroupConfigsApi, getGroupConfigsApi } from '@/api/configs/productConfig';

const configGroupName = "attribute";

const props = defineProps<{
  productId: number;
}>();

// 定义配置项类型
interface ConfigItem {
  configKey: string;
  configValue: string[]; // 存储多选值数组
  configDesc: string;
}

// 物联网参数选项（实际项目中可能从后端获取）
const paramOptions = [
  { label: '温度', value: 'temperature' },
  { label: '湿度', value: 'humidity' },
  { label: '压力', value: 'pressure' },
  { label: '电流', value: 'current' },
  { label: '电压', value: 'voltage' },
  { label: '功率', value: 'power' }
];

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();
// 添加全选状态变量
const isAllChecked = ref(false);

// 初始化表单数据
const formData = reactive<{
  productId: number;
  productName: string;
  groupName: string;
  configs: ConfigItem[];
  updatedAt: string;
}>({
  productId: 0,
  productName: "",
  groupName: configGroupName,
  configs: [
    { configKey: 'attributes', configValue: [], configDesc: '包含参数' }
  ],
  updatedAt: ''
});

// 监听选中值变化，更新全选状态
watch(
  () => formData.configs[0].configValue,
  (newVal) => {
    isAllChecked.value = newVal.length > 0 && newVal.length === paramOptions.length;
  },
  { immediate: true }
);

// 全选/取消全选方法
const handleCheckAll = (checked: boolean) => {
  formData.configs[0].configValue = checked
    ? paramOptions.map(option => option.value)
    : [];
};

// 表单验证规则
const rules = reactive({
  productId: [{ required: true, message: '请选择产品', trigger: 'blur' }],
  groupName: [{ required: true, message: '请输入配置组名', trigger: 'blur' }],
  'configs.0.configValue': [
    {
      required: true,
      message: '请至少选择一个参数',
      trigger: 'change'
    }
  ]
});
watch(() => props.productId, (newVal:number) => {
  if (newVal) {
    formData.productId = newVal;
    loadConfigData();
  }
},{
  deep: true
});
const loadConfigData = () => {
  if(formData.productId){
    // 获取产品配置组数据
    getGroupConfigsApi({
      productId: formData.productId,
      groupName: formData.groupName
    }).then(res => {
      if (res.code === 0) {
        formData.updatedAt = res.data?.updatedAt || '';

        // 合并配置数据（将字符串转换为数组）
        if (Array.isArray(res.data?.configs)) {
          res.data.configs.forEach(item => {
            const target = formData.configs.find(cfg => cfg.configKey === item.configKey);
            if (target) {
              // 假设后端存储的是逗号分隔的字符串
              target.configValue = item.configValue ? item.configValue.split(',') : [];
              target.configDesc = item.configDesc || target.configDesc;
            }
          });
        }
      }
    });
  }
}


// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    // 1. 先进行表单验证
    await formRef.value.validate();

    // 2. 验证通过后显示二次确认框
    ElMessageBox.confirm(
      '确定要保存当前属性配置吗？',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      // 3. 用户确认后执行提交（将数组转换为逗号分隔的字符串）
      const submitData = {
        productId: formData.productId,
        groupName: formData.groupName,
        configs: formData.configs.map(item => ({
          ...item,
          configValue: item.configValue.join(',') // 转换为字符串
        }))
      };

      await setGroupConfigsApi(submitData);
      ElMessage.success('保存成功');
    }).catch(() => {
      // 用户取消提交
      ElMessage.info('已取消保存');
    });
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="160px" class="form-container">
    <el-form-item label="产品名称" prop="productName">
      <el-input v-model="formData.productName" placeholder="请输入产品" disabled />
    </el-form-item>
    <el-form-item label="配置组名" prop="groupName">
      <el-input v-model="formData.groupName" placeholder="请输入配置组名" disabled/>
    </el-form-item>

    <!-- 属性配置项 - 多选框组（添加全选按钮） -->
    <el-form-item label="包含参数" prop="configs.0.configValue">
      <div class="checkbox-all-container">
        <el-checkbox
          v-model="isAllChecked"
          @change="handleCheckAll"
          style="margin-bottom: 15px;"
        >
          全选
        </el-checkbox>
      </div>
      <el-checkbox-group v-model="formData.configs[0].configValue">
        <el-checkbox
          v-for="option in paramOptions"
          :key="option.value"
          :label="option.value"
          style="margin-right: 20px; margin-bottom: 10px;"
        >
          {{ option.label }}
        </el-checkbox>
      </el-checkbox-group>
      <div class="form-hint">提示：请选择该产品包含的物联网参数</div>
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item label="更新时间" v-if="formData.updatedAt">
      <el-input v-model="formData.updatedAt" disabled placeholder="暂无更新时间" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}
.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 30px;
}
.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}
::v-deep .el-form-item__content {
  flex: 1;
}
::v-deep .el-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
}
.checkbox-all-container {
  margin-bottom: 10px;
}
</style>
